# 导入请求
import requests
import lxml.html
import time
#获取验证码的url, 一般指登录页面
loginUrl = 'http://exercise.kingname.info/exercise_captcha.html'

# 登录方法
login_url = 'http://exercise.kingname.info/exercise_captcha_check'

saveImage = str(time.time()) +'_captcha.png'

def saveImageToFile (session,codeUrl,saveFilePath):
    print(f' 登录页面地址: {codeUrl} 保存路径: {saveFilePath}')
    codeContent = session.get(codeUrl).content.decode()
    print(f'内容是: {codeContent}')
    selector = lxml.html.fromstring(codeContent)
    captcha_url = selector.xpath('//img/@src')[0]
    image = requests.get('http://exercise.kingname.info/' + captcha_url).content
    # 获取内容，以图片方式进行保存
    with open(saveFilePath,'wb') as f:
        f.write(image)
        print(f'保存到路径: {saveFilePath}')
# 获取到验证码, 要使用session
session = requests.Session()
saveImageToFile(session,loginUrl,saveImage)
time.sleep(3)
captcha = input(f'请查看 {saveImage}的验证码内容,然后输入到这里:')
data = {
    'captcha': captcha
}
print(f'\n 输入数据: {captcha} \n')
loginResponse = session.post(login_url,data= data)
print(f'输入验证码之后，网站返回 {loginResponse.content.decode()}')